import SerializeAble, { CSMemberType, Serialize, SerializeClass } from "../../core/serialize";
import { Action } from "./action";
import { Condition } from "./condition";
import { Event } from "./event";

@SerializeClass("ECA")
export class ECA extends SerializeAble {
    @Serialize(Event, CSMemberType.Array)
    evts: Event[] = [];
    @Serialize(Condition, CSMemberType.Array)
    conditions: Condition[] = [];
    // @Serialize(Action, CSMemberType.Array)
    // actions: Action[] = [];

    obj: any = null;
    init(obj: any) {
        this.obj = obj;

        this.evts.forEach(evt => {
            let hook = evt.hook(this.obj);
            hook.onTrigged = this.triggerWithCondition.bind(this);
        });
    }
    triggerWithCondition(evt: Event, ...args: any[]) {
        // console.log(`ECA->触发(${evt.name})`);
        for (let i = 0; i < this.conditions.length; i++) {
            let cond = this.conditions[i];
            if (!cond.check(this.obj, ...args)) {
                // console.log(`ECA->不满足条件(${cond.name})`);
            }
            else {
                // console.log(`ECA->满足条件(${cond.name})`);
                this.runActions(cond.actions, ...args);
                break;
            }
        }
    }
    async runActions(actions: Action[], ...args: any[]) {
        for (let i = 0; i < actions.length; i++) {
            let action = actions[i];
            // console.log(`ECA->执行动作:(${action.name})`);
            await action.run(this.obj, ...args);
        }
    }
};